package com.amos.muexamclient.common;

import com.amos.bean.Result;
import com.amos.constant.Constants;
import com.amos.exception.BizExceptionEnum;
import com.amos.muexamclient.framework.service.RedisService;
import com.amos.util.Base64;
import com.amos.util.StringUtils;
import com.amos.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright © 2018 嘉源锐信. All rights reserved.
 *
 * @Project: mu-exam
 * @ClassName: CaptchaController
 * @Package: com.amos.muexamclient.common
 * @author: zhuqb
 * @Description:
 * @date: 2020/3/24 0024 下午 14:51
 * @Version: V1.0
 */
@RestController
public class CaptchaController {

    @Autowired
    private RedisService redisService;

    /**
     * 生成验证码
     *
     * @param response
     * @return
     */
    @GetMapping("/captchaImage")
    public Result captchaImage(HttpServletResponse response) {
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        String uuid = StringUtils.generateUuid();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        redisService.save(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION);

        Map<String, String> resultMap = new HashMap<>(2);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
            resultMap.put("uuid", uuid);
            resultMap.put("img", Base64.encode(stream.toByteArray()));
            return Result.success(resultMap);
        } catch (IOException e) {
            e.printStackTrace();
            BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("生成验证码出错").throwException();
        }
        return Result.error("系统异常");
    }
}
